package com.learn.configuration;

import com.learn.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.persistence.Entity;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private AdminService adminService;
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers(HttpMethod.POST);
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("**/**","/","**").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().usernameParameter("userName").passwordParameter("password")
                .loginPage("/admin/login").defaultSuccessUrl("/admin/home").permitAll()
                .and().logout().logoutUrl("/admin/logout").logoutSuccessUrl("/admin/login").permitAll()
                .and().httpBasic()
                .and().csrf().disable();
    }

    @Autowired
    public void configure(AuthenticationManagerBuilder builder) throws Exception{
        builder.userDetailsService(adminService)
            .passwordEncoder(passwordEncoder());
    }

    /**
     * 设置用户密码的加密方式为MD5加密
     * @return
     */
    @Bean
    public Md5PasswordEncoder passwordEncoder() {
        return new Md5PasswordEncoder();
    }

}
